package org.codehaus.activemq.transport;

import java.io.IOException;
import java.net.URI;
import javax.jms.JMSException;
import org.codehaus.activemq.message.WireFormat;
import org.codehaus.activemq.util.FactoryFinder;

public class TransportChannelProvider
{
  private static FactoryFinder finder = new FactoryFinder("META-INF/services/org/codehaus/activemq/transport/");

  public static TransportChannel create(WireFormat wireFormat, URI remoteLocation)
    throws JMSException
  {
    return getFactory(remoteLocation).create(wireFormat, remoteLocation);
  }

  public static TransportChannel create(WireFormat wireFormat, URI remoteLocation, URI localLocation)
    throws JMSException
  {
    return getFactory(remoteLocation).create(wireFormat, remoteLocation, localLocation);
  }

  public static TransportChannelFactory getFactory(URI remoteLocation) throws JMSException {
    String protocol = remoteLocation.getScheme();
    try {
      Object value = finder.newInstance(protocol);
      if ((value instanceof TransportChannelFactory)) {
        return (TransportChannelFactory)value;
      }

      throw new JMSException("Factory does not implement TransportChannelFactory: " + value);
    }
    catch (IllegalAccessException e)
    {
      throw createJMSexception(protocol, e);
    }
    catch (InstantiationException e) {
      throw createJMSexception(protocol, e);
    }
    catch (IOException e) {
      throw createJMSexception(protocol, e);
    } catch (ClassNotFoundException e) {
    	throw createJMSexception(protocol, e);
    }
    
  }

  protected static JMSException createJMSexception(String protocol, Exception e)
  {
    JMSException answer = new JMSException("Could not load protocol: " + protocol + ". Reason: " + e);
    answer.setLinkedException(e);
    return answer;
  }
}